<template>
    <el-dialog :visible.sync="is_edit_group_form_show" :before-close="handleClose">
        <el-form class="dialog-form" ref="form" :model="form" label-width="120px">
            <el-form-item label="平台名称：" prop="name" :rules="[{required: true, message: '请修改名称', trigger: 'change'}]">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="我方开放部门：">
                <el-tree ref="edit-group-manage-tree" check-strictly :data="sys_department_tree" show-checkbox node-key="id" :props="props" :default-expanded-keys="check_list"></el-tree>
            </el-form-item>
            <el-form-item>
                <el-button @click="handleClose">取消</el-button>
                <el-button @click="onSubmit('form')" type="primary">确定</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script>
import group from '@/api/group.js'
import { mapGetters } from 'vuex'

export default {
    name: 'edit-group',
    props: ['is_edit_group_form_show', 'data'],
    computed: {
        ...mapGetters('department1', ['sys_department_tree'])
    },
    data() {
        return {
            form: {
                id: undefined,
                name: undefined
            },
            props: {
                children: 'children',
                value: 'id',
                label: 'text'
            },
            check_list: undefined
        }
    },
    methods: {
        handleClose() {
            this.$refs['edit-group-manage-tree'].setCheckedKeys([]);
            this.$emit('update:is_edit_group_form_show', false)
        },
        onSubmit(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    let params = {
                        id: this.form.id,
                        groupName: this.form.name
                    }
                    await group.editGroup(params).then(res => {
                        this.$message({
                            type: 'success',
                            message: '编辑成功!'
                        });
                        this.$store.dispatch('group/getGroupList');
                    }).catch(err => {
                        this.$message.error(err);
                    })
                    params = null;
                    this.handleClose();
                } else {
                    return false;
                }
            })
        }
    },
    watch: {
        data(newVal) {
            this.form.id = newVal.id;
            this.form.name = newVal.groupName;
            this.check_list = newVal.department;
            this.$refs['edit-group-manage-tree'].setCheckedKeys(newVal.department);
        }
    },
    mounted() {
        if(this.sys_department_tree === undefined) {
            this.$store.dispatch('department1/getSysDepartmentTree');
        }
    }
}
</script>

<style>

</style>
